import React, { useEffect, useState } from "react";
import { MainLayout, LazyloadImage } from "../../components";
import { Button, Table, Typography, Space } from "antd";
import { fetchList } from "../../api";

import "./style.css";
import { Navigate, useNavigate } from "react-router-dom";
import { useClickWidthLogin } from "../../hooks";
interface ResultChilrenType {
  id: string;
  src: string;
  title: string;
  content: string;
  avator: string;
  auther: string;
}

interface ResultType {
  type: string;
  children: ResultChilrenType[];
}

const Index = () => {
  const titles = [
    "全部",
    "去中心化应用",
    "公链",
    "联盟链",
    "layer2",
    "编程语言",
  ];
  const [result, setResult] = useState<ResultType>({ type: "", children: [] });

  const [type, setType] = useState("全部");
  const naviagate = useNavigate();
  const getData = async () => {
    const resp = await fetchList({ type });
    setResult(resp.data.data);
  };

  const onClick = useClickWidthLogin(() => {
    naviagate("/publish");
  });

  useEffect(() => {
    getData();
  }, [type]);

  return (
    <MainLayout>
      <div className="title">
        <Space>
          {titles.map((v, i) => {
            return (
              <Button
                key={i}
                type={type === v ? "primary" : "default"}
                onClick={() => setType(v)}
              >
                {v}
              </Button>
            );
          })}
        </Space>
        <Button type="primary" onClick={() => onClick()}>
          发布文章
        </Button>
      </div>
      <div className="content">
        <Table dataSource={result.children} rowKey={(row) => row.id}>
          <Table.Column
            render={(_: ResultChilrenType) => {
              return (
                <div
                  className="list-item"
                  onClick={() => naviagate(`/detail/${_.id}`, {
                    state: _
                  })}
                >
                  <dl>
                    <dt>
                      <LazyloadImage src={_.src} width={300} height={200} />
                    </dt>
                    <dd style={{ marginLeft: 10 }}>
                      <h2>{_.title}</h2>
                      <Typography.Paragraph ellipsis={{ rows: 4 }}>
                        {_.content}
                      </Typography.Paragraph>
                      <div>
                        <img
                          src={_.avator}
                          alt=""
                          style={{ borderRadius: "50%" }}
                          width={40}
                          height={40}
                        />
                        <span>{_.auther}</span>
                      </div>
                    </dd>
                  </dl>
                </div>
              );
            }}
          ></Table.Column>
        </Table>
      </div>
    </MainLayout>
  );
};

export default Index;
